#include "xmppim/connectionthread.h"

namespace yoohoo_xmppim {

ConnectionThread::ConnectionThread(Connection* connection, QObject* parent) : QThread(parent) {
	_connection = connection;
}

ConnectionThread::~ConnectionThread() {
	qDebug("quit connection thread");
	quit();
}

void ConnectionThread::setConnection(Connection* connection) {
	_connection = connection;
}

Connection* ConnectionThread::connection() {
	return _connection;
}

void ConnectionThread::start() {
	if (isRunning())
		return;

	Q_ASSERT(_connection);
	QThread::start();
}

void ConnectionThread::quit() {
	if (!isRunning())
		return;

	QMetaObject::invokeMethod(_connection, "disconnectFromHost", Qt::BlockingQueuedConnection);

	QThread::quit();
	while (isRunning()) {
		qDebug("ConnectionThread::quit: Waitting to exit");
		wait(50);
	}
}

void ConnectionThread::run() {
	exec();
}

}
